<?php

namespace Plugins\AdminBasic\Http\Admin\Controller;

use App\Http\AbstractController;
use App\Middlewares\Admin\AuthenticateMiddleware;
use App\Middlewares\Admin\PermissionsMiddleware;
use App\Util\Helper;
use App\Util\Response;
use App\Util\Response\Json;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Redis\Redis;
use Psr\Http\Message\MessageInterface;
use Psr\Http\Message\ResponseInterface;
use Sc\Util\MysqlDataBackup\Backup;
use Sc\Util\MysqlDataBackup\Connect;

/**
 * 数据备份
 *
 * Class DataBackUpController
 */
#[Controller(prefix: 'admin/plugins/admin-basic/backup')]
#[Middlewares([AuthenticateMiddleware::class, PermissionsMiddleware::class])]
class DataBackUpController extends AbstractController
{
    /**
     * 备份
     *
     * @return Json|MessageInterface|ResponseInterface
     * @throws \Exception
     */
    #[RequestMapping(path: 'back-up')]
    public function backup(): Response\Json|MessageInterface|ResponseInterface
    {
        $database   = Helper::getConfig('databases.default');
        $backupDir  = $database['backup']['dir'] ?: 'storage/data';
        $backupDir  = strtr(BASE_PATH . '/' . $backupDir, ['//' => '/']);
        $verifyCode = $database['backup']['verifyCode'] ?: "";

        $RConnect = new Connect($database['database'], $database['host'], $database['username'], $database['password'], $database['port']);
        $backUp   = new Backup($RConnect, $backupDir, md5($verifyCode), Helper::getContainer(Redis::class));
        $result   = $backUp->render(Helper::request()->post());

        if (is_string($result)) {
            return Response::raw($result)->withHeader('Content-Type', 'text/html');
        }

        return Response::json($result);
    }
}